<style>
</style>
<template>
<Row class="layout-content-body" id="print-pdf">
  <dtable :columnsList="columns" v-model="dataAll" :totals="total" add check op delCheck :hover-show="true" :edit-incell="true" @add="salesAdd" @input="input" @del="salesDel" @edit="salesEdit" :loading="loading" :pageS="100"></dtable>
  <!-- <Modal title="客户" v-model="custShow" @on-ok="custOk" width=80>
    <cust @handelSelect="custSelect"></cust>
  </Modal>
  <Modal title="产品" v-model="prodShow" @on-ok="prodOk" width=80 class-name="prodShow">
    <prod @handelSelect="prodSelect"></prod>
  </Modal>
  <Modal title="单据明细" v-model="salesShow" @on-ok="salesOk">
    <Form ref="formSales" :model="formSales" :label-width="80">
      <Form-item label="产品" prop="Name">
        <Input v-model="formSales.Name" placeholder="请输入" :disabled="!salesAd" @on-focus="prodEdit"></Input>
      </Form-item>
      <Form-item label="数量" prop="Count">
        <InputNumber :min="1" v-model.number="formSales.Count"></InputNumber>
      </Form-item>
      <Form-item label="单价" prop="Price">
        <Input v-model.number="formSales.Price" disabled>
        </Input>
      </Form-item>
      <Form-item label="优惠价" prop="DiscountPrice">
        <Input v-model.number="formSales.DiscountPrice">
        </Input>
      </Form-item>
      <Form-item label="说明" prop="Remark">
        <Input v-model="formSales.Remark">
        </Input>
      </Form-item>
    </Form>
  </Modal> -->
</Row>
</template>

<script>
import { getData } from "@/common/utils";
import { currency } from "@/common/filter";
import dtable from "@/components/table/etable.vue"; //
import cust from "@/views/busy/cust";
import prod from "@/views/busy/prod";
var list = [];
var item = {};
export default {
  name: "engineeritem",
  data() {
    return {
      loading: false, //数据刷新遮罩层
      //表格样式
      columns: [
        {
          title: "姓名",
          key: "Name",
          fixed: "left",
          width: 100,
          render: (h, params) => {
            return h("div", [
              h("Icon", {
                props: {
                  type: "person"
                }
              }),
              h("strong", params.row.Name)
            ]);
          }
        },
        {
          title: "性别",
          key: "Sex",
          width: 80,
          render: (h, { row }) => {
            return h("span", {}, row.Sex == 1 ? "男" : "女");
          }
        },
        {
          title: "出生年月",
          key: "Birth",
          width: 100,
          render: (h, { row, column, index }) => {
            return h("span", {}, moment(row.Birth).format("YYYY-MM-DD"));
          }
        },
        {
          title: "学历获得",
          key: "Xuelihuode",
          width: 80,
          render: (h, { row }) => {
            let str = "";
            switch (row.Xuelihuode) {
              case 1:
                str = "函授";
                break;
              case 2:
                str = "全日制";
                break;
              case 3:
                str = "成人";
                break;
              default:
                str = "其它";
                break;
            }
            return h("span", {}, str);
          }
        },
        {
          title: "毕业院校及专业",
          width: 150,
          key: "Biyeyuanxiaojizhuanye"
        },
        {
          title: "毕业时间",
          key: "Biyeshijian",
          width: 100,
          render: (h, { row, column, index }) => {
            return h("span", {}, moment(row.Biyeshijian).format("YYYY-MM-DD"));
          }
        },
        {
          title: "参加工作时间及单位",
          key: "Gongzuoshijiandanwei",
          width: 150
        },
        {
          title: "参加技术工作时间及单位",
          key: "Jishugongzuoshijiandanwei",
          width: 150
        },
        {
          title: "现从事专业",
          key: "Xianzhuanye",
          width: 150
        },
        {
          title: "取得专业技术资格及时间",
          key: "Qudejishuzigeshijian",
          width: 150
        },
        {
          title: "是否具有鉴定资格",
          key: "Jaindingzige",
          render: (h, { row, column, index }) => {
            return h("span", {}, row.Jaindingzige == 1 ? "是" : "否");
          }
        },
        {
          title: "现所在单位",
          key: "Suozaibumen"
        },
        {
          title: "是否现场勘察人员",
          key: "Kancha",
          render: (h, { row, column, index }) => {
            return h("span", {}, row.Kancha == 1 ? "是" : "否");
          }
        }
      ],
      summary: {
        Name: "合计",
        Money: 0
      },
      dataAll: [], //表格数据来源含合计
      datas: [], //表格数据来源
      formItem: {
        Id: "",
        Name: "",
        CustName: "",
        Remark: "",
        Price: 0,
        Receiv: [],
        Sales: [],
        ReceivTime: 0,
        DiscountPrice: 0,
        Off: 0
      }, //数据编辑表单
      formSales: {
        Id: "",
        Name: "",
        Count: 1,
        Remark: "",
        Price: 0,
        DiscountPrice: 0,
        Off: 0
      },
      ruleValidate: {
        Name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }
        ]
      }, //数据编辑表单验证规则
      addid: true, //true为修改模式，false为添加模式
      salesAd: false,
      custShow: false,
      prodShow: false,
      salesShow: false,
      recive: [],
      PercentShow: "always",
      cust: [],
      prod: [],
      total: 0,
      orderData: this.$route.params.orderData
    };
  },
  components: {
    dtable,
    cust,
    prod
  },
  computed: {},
  props: {},
  watch: {},
  methods: {
    getSummaryMoney() {
      let sum = 0;
      if (this.datas) {
        for (let m in this.datas) {
          sum = sum + this.datas[m].Money;
        }
      }
      return sum;
    },
    getall() {
      if (!this.orderData) {
        this.$router.push({
          name: "销售订单"
        });
        return;
      }
      this.loading = true;
      this.dataAll.pop();
      if (this.orderData.edit) {
        this.formItem = getData(this.orderData.order);
        this.$api.getSales(this.orderData.order.Id).then(res => {
          if (!res.error) {
            this.datas = res.Data.sales;
            this.recive = getData(res.Data.receiv);
            this.ReceivePercent();
            if (this.datas) {
              for (let e in this.datas) {
                this.datas[e].Money =
                  this.datas[e].DiscountPrice * this.datas[e].Count;
              }
              this.total = this.datas.length;
            }
            this.dataAll = getData(this.datas);
            this.formItem.Sales = getData(this.datas);
            this.summary.Money = this.getSummaryMoney();
            this.dataAll.push(this.summary);
            // this.loading = false;
          } else {
            this.$Message.error(res.message);
          }
        });

        this.loading = false;
      } else {
        if (this.orderData.temp) {
          this.$api.getTempitem(this.orderData.temp).then(res => {
            if (!res.error) {
              this.datas = getData(res.Data);
              if (this.datas) {
                for (let e in this.datas) {
                  this.datas[e].Money =
                    this.datas[e].Price * this.datas[e].Count;
                  this.datas[e].DiscountPrice = this.datas[e].Price;
                }
                this.total = this.datas.length;
                this.dataAll = getData(this.datas);
              } else {
                this.dataAll = [];
                this.datas = [];
                this.total = this.dataAll.length;
              }
              this.summary.Money = this.getSummaryMoney();
              this.dataAll.push(this.summary);
              this.ReceivPlus();
              // this.loading = false
            } else {
              this.$Message.error(res.message);
            }
          });
        }
        // this.summary.Money = this.getSummaryMoney()
        // this.dataAll.push(this.summary)
        this.loading = false;
      }
    },

    salesEdit(index) {
      this.salesAd = false;
      this.formSales = index;
      this.salesShow = true;
    },
    salesAdd() {
      this.salesAd = true;
      this.$refs["formSales"].resetFields();
      this.salesShow = true;
    },
    salesOk() {
      this.formSales.Money =
        this.formSales.DiscountPrice * this.formSales.Count;
      this.dataAll = [];
      item = getData(this.formSales);
      if (this.salesAd) {
        this.datas = this.findProdAdd(this.datas, item);
        // this.dataAll=this.findProdAdd(this.dataAll,item)
      } else {
        this.datas = this.findProdEdit(this.datas, item);
      }
      this.dataAll = getData(this.datas);
      this.summary.Money = this.getSummaryMoney();
      this.dataAll.push(this.summary);
      this.formItem.Price = this.summary.Money;
      this.formItem.DiscountPrice = this.summary.Money;
      this.formItem.Off = this.formItem.Price - this.formItem.DiscountPrice;
      this.formItem.Sales = this.datas;
      this.salesShow = false;
    },
    salesDel(row) {
      this.$api.deleteProdType(row).then(res => {
        if (!res.error) {
          this.getall();
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message, 4);
        }
      });
    },
    salesDelCheck(row) {},
    input(data) {
      // console.log(data)
      // this.dataAll = []
      this.datas = getData(data);
      this.datas.pop();
      this.datas = this.inputEdit(this.datas);
      this.dataAll = getData(this.datas);
      this.summary.Money = this.getSummaryMoney();
      this.dataAll.push(this.summary);
      this.formItem.Price = this.summary.Money;
      this.formItem.DiscountPrice = this.summary.Money;
      this.formItem.Off = this.formItem.Price - this.formItem.DiscountPrice;
      this.formItem.Sales = this.datas;
      this.salesShow = false;
    },
    custEdit() {
      this.custShow = true;
    },
    custOk() {
      if (this.cust.length > 1) {
        this.$Message.error("客户只能选择一个");
      } else {
        console.log(this.cust[0]);
        this.formItem.CustId = this.cust[0].Id;
        this.formItem.CustName = this.cust[0].Name;
        this.formItem.Contact = this.cust[0].CustName;
        this.formItem.Address = this.cust[0].Address;
        this.formItem.Phone = this.cust[0].Phone;
        console.log(this.formItem);
      }
    },
    custSelect(selection) {
      // console.log(selection[0])
      if (selection.length > 1) {
        this.$Message.error("客户只能选择一个");
      }
      this.cust = selection;
    },
    prodEdit() {
      this.prodShow = true;
    },
    prodOk() {
      if (this.prod.length > 1) {
        this.$Message.error("产品只能选择一个");
      } else {
        this.formSales.ProdId = this.prod[0].Id;
        this.formSales.Price = this.prod[0].Price;
        this.formSales.DiscountPrice = this.prod[0].Price;
        this.formSales.Name = this.prod[0].Name;
        this.formSales.Cost = this.prod[0].Cost;
        this.formSales.Model = this.prod[0].Model;
        this.formSales.Spec = this.prod[0].Spec;
        this.formSales.Off =
          this.formSales.Price - this.formSales.DiscountPrice;
      }
    },
    prodSelect(selection) {
      // console.log(selection[0])
      if (selection.length > 1) {
        this.$Message.error("产品只能选择一个");
      }
      this.prod = selection;
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid && this.ReceiveOK()) {
          this.formItem.Receiv = getData(this.recive);
          if (!this.orderData.edit) {
            this.$api.addOrder(this.formItem).then(res => {
              if (!res.error) {
                this.$Message.success(res.message);
                this.$router.push({
                  name: "销售订单"
                });
              } else {
                this.$Message.error(res.message, 4);
              }
            });
          } else {
            console.log(this.formItem);
            this.formItem.Price = this.summary.Money;
            this.$api.updateOrder(this.formItem).then(res => {
              if (!res.error) {
                this.$Message.success(res.message);
                this.$router.push({
                  name: "销售订单"
                });
              } else {
                this.$Message.error(res.message, 4);
              }
            });
          }
        } else {
          this.$Message.error("表单验证失败或付款金额与总额不符!");
        }
      });
    },
    handleReset(name) {
      this.$router.push({
        name: "销售订单"
      });
    },
    findProdAdd(array, x) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        if (array[pos].ProdId === x.ProdId) {
          //未找到就退出循环完成搜索
          array[pos].Count = array[pos].Count + x.Count;
          array[pos].Money = array[pos].DiscountPrice * array[pos].Count;
          break;
        }
        pos += 1; //并从下个位置开始搜索
      }
      if (pos === len) {
        array.push(x);
      }
      return array;
    },
    findProdEdit(array, x) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        if (array[pos].ProdId === x.ProdId) {
          //未找到就退出循环完成搜索
          array[pos].Count = x.Count;
          array[pos].Money = array[pos].DiscountPrice * array[pos].Count;
          break;
        }
        pos += 1; //并从下个位置开始搜索
      }
      return array;
    },
    inputEdit(array) {
      var len = array.length,
        pos = 0;
      while (pos < len) {
        array[pos].Count = Number(array[pos].Count);
        array[pos].Money = array[pos].DiscountPrice * array[pos].Count;
        pos += 1; //并从下个位置开始搜索
      }
      return array;
    },
    getindex(data) {
      return data + 1;
    },
    ReceivPlus() {
      let rc = {
        Seq: 1,
        Date: "",
        Money: 0,
        Remark: ""
      };
      let len = this.recive.length;
      if (len > 0) {
        rc.Seq = this.recive[len - 1].Seq + 1;
      }
      this.recive.push(rc);
    },
    ReceivMinus() {
      this.recive.pop();
    },
    ReceiveOK() {
      let ok = false,
        len = this.recive.length,
        pos = 0,
        sum = this.ReceiveSum();
      while (pos < len) {
        this.recive[pos].Money =
          this.formItem.DiscountPrice * this.recive[pos].Percent / 100;
        pos += 1; //并从下个位置开始搜索
      }
      console.log(sum);
      console.log(this.formItem);
      console.log(this.recive);
      if (100 === sum) {
        ok = true;
      }
      return ok;
    },
    ReceiveSum() {
      let len = this.recive.length,
        pos = 0,
        sum = 0;
      while (pos < len) {
        sum = sum + this.recive[pos].Percent;
        pos += 1; //并从下个位置开始搜索
      }
      return sum;
    },
    ReceivePercent() {
      let len = this.recive.length,
        pos = 0;
      let sum = this.formItem.DiscountPrice;
      while (pos < len) {
        this.recive[pos].Percent = this.recive[pos].Money / sum * 100;
        pos += 1; //并从下个位置开始搜索
      }
      return;
    },
    formatPercent(val) {
      return (
        "付款比例: " +
        val +
        "%;" +
        "付款金额：" +
        this.formItem.DiscountPrice * val / 100
      );
    },
    printContent(e) {
      let subOutputRankPrint = document.getElementById("print-pdf");
      console.log(subOutputRankPrint.innerHTML);
      let newContent = subOutputRankPrint.innerHTML;
      let oldContent = document.body.innerHTML;
      document.body.innerHTML = newContent;
      window.print();
      window.location.reload();
      document.body.innerHTML = oldContent;
      return false;
    }
  },
  mounted() {
    // this.getall();
    // console.log(this.formItem.Receiv)
  }
};
</script>
